<template>
  <el-container class="main-layout">
    <!-- 顶部导航栏 -->
    <el-header class="header">
      <div class="header-left">
        <!-- Logo和系统名称 -->
        <div class="logo-section">
          <el-icon class="logo-icon" size="24">
            <House />
          </el-icon>
          <span class="system-name">Thailand Recharge System</span>
        </div>
      </div>

      <div class="header-right">
        <!-- Network Status Indicator -->
        <el-tag v-if="!isOnline" type="danger" size="small" class="status-tag">
          <el-icon><Warning /></el-icon>
          Offline
        </el-tag>

        <!-- 用户信息下拉菜单 -->
        <el-dropdown @command="handleUserMenuCommand" class="user-dropdown">
          <span class="user-info">
            <el-avatar :size="32" class="user-avatar">
              <img v-if="authStore.user?.avatar" :src="authStore.user.avatar" :alt="authStore.user?.username" />
              <el-icon v-else><User /></el-icon>
            </el-avatar>
            <span class="username">{{ authStore.user?.username }}</span>
            <el-icon class="dropdown-icon"><ArrowDown /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="logout">
                <el-icon><SwitchButton /></el-icon>
                Logout
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-header>

    <el-container class="body-container">
      <!-- 侧边栏 -->
      <el-aside :width="sidebarWidth" class="sidebar">
        <el-menu :default-active="activeMenu" :collapse="isCollapse" :unique-opened="true" router class="sidebar-menu">
          <!-- Dashboard -->
          <el-menu-item index="/dashboard">
            <el-icon><Odometer /></el-icon>
            <template #title>Dashboard</template>
          </el-menu-item>

          <!-- Customer Management -->
          <el-menu-item index="/customers" v-if="canAccessCustomerManagement">
            <el-icon><UserFilled /></el-icon>
            <template #title>Customer Management</template>
          </el-menu-item>

          <!-- Recharge Management -->
          <el-sub-menu index="recharge" v-if="canAccessRechargeManagement">
            <template #title>
              <el-icon><Money /></el-icon>
              <span>Recharge Management</span>
            </template>
            <el-menu-item index="/recharge/create">
              <el-icon><Plus /></el-icon>
              <template #title>Create Order</template>
            </el-menu-item>
            <el-menu-item index="/recharge/query">
              <el-icon><Search /></el-icon>
              <template #title>Query Orders</template>
            </el-menu-item>
          </el-sub-menu>

          <!-- Payout Management -->
          <el-sub-menu index="payout" v-if="canAccessPayoutManagement">
            <template #title>
              <el-icon><Wallet /></el-icon>
              <span>Payout Management</span>
            </template>
            <el-menu-item index="/payout/create">
              <el-icon><Plus /></el-icon>
              <template #title>Create Payout</template>
            </el-menu-item>
            <el-menu-item index="/payout/query">
              <el-icon><Search /></el-icon>
              <template #title>Query Payouts</template>
            </el-menu-item>
          </el-sub-menu>

          <!-- System Management -->
          <el-sub-menu index="system" v-if="canAccessAdminSettings">
            <template #title>
              <el-icon><Setting /></el-icon>
              <span>System Management</span>
            </template>
            <el-menu-item index="/admin/settings">
              <el-icon><Lock /></el-icon>
              <template #title>Admin Settings</template>
            </el-menu-item>
            <el-menu-item index="/admin/quick-amounts">
              <el-icon><PriceTag /></el-icon>
              <template #title>Quick Amount Settings</template>
            </el-menu-item>
            <el-menu-item index="/admin/purchase-price">
              <el-icon><Money /></el-icon>
              <template #title>Purchase Price Config</template>
            </el-menu-item>
            <el-menu-item index="/admin/channel-config">
              <el-icon><DataBoard /></el-icon>
              <template #title>Payment Channel Config</template>
            </el-menu-item>
            <el-menu-item index="/admin/product-config">
              <el-icon><Grid /></el-icon>
              <template #title>Product Config</template>
            </el-menu-item>
          </el-sub-menu>
        </el-menu>
      </el-aside>

      <!-- 主内容区域 -->
      <el-main class="main-content">
        <!-- 页面内容 -->
        <div class="page-content">
          <router-view />
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue"
import { useRoute, useRouter } from "vue-router"
import { useAuthStore } from "../stores/auth"
import { getGlobalState } from "../composables/useGlobalState"
import { PermissionUtils } from "../utils/permissions"
import { ElMessage, ElMessageBox } from "element-plus"
import { House, Warning, User, SwitchButton, ArrowDown, Odometer, UserFilled, Money, Plus, Search, Wallet, Setting, Lock, PriceTag, DataBoard, Grid } from "@element-plus/icons-vue"

// 路由和store
const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()
const globalState = getGlobalState()

// 响应式数据
const isCollapse = ref(false)

// 计算属性
const isOnline = computed(() => globalState.isOnline)
const sidebarWidth = computed(() => (isCollapse.value ? "64px" : "260px"))
const activeMenu = computed(() => route.path)

// 权限检查
const canAccessCustomerManagement = computed(() => PermissionUtils.canAccessModule(authStore.user, "user_management"))

const canAccessRechargeManagement = computed(() => PermissionUtils.canAccessModule(authStore.user, "recharge_management"))

const canAccessPayoutManagement = computed(() => PermissionUtils.canAccessModule(authStore.user, "payout_management"))

const canAccessAdminSettings = computed(() => PermissionUtils.isAdmin(authStore.user))

async function handleUserMenuCommand(command: string) {
  switch (command) {
    case "logout":
      try {
        await ElMessageBox.confirm("Are you sure you want to logout?", "Confirm Logout", {
          confirmButtonText: "Logout",
          cancelButtonText: "Cancel",
          type: "warning",
        })

        await authStore.logout()
        ElMessage.success("Logged out successfully")
        router.push("/login")
      } catch (error) {
        // User cancelled logout
        if (error !== "cancel") {
          console.error("Logout failed:", error)
          ElMessage.error("Logout failed")
        }
      }
      break
  }
}

// 监听路由变化，自动收起移动端侧边栏
watch(
  () => route.path,
  () => {
    // 在移动端自动收起侧边栏
    if (window.innerWidth < 768) {
      isCollapse.value = true
    }
  }
)
</script>

<style scoped>
.main-layout {
  height: 100vh;
}

.header {
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.logo-section {
  display: flex;
  align-items: center;
  gap: 8px;
}

.logo-icon {
  color: var(--el-color-primary);
}

.system-name {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.collapse-btn {
  color: #606266;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.status-tag {
  display: flex;
  align-items: center;
  gap: 4px;
}

.user-dropdown {
  cursor: pointer;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: var(--el-color-primary-light-9);
}

.user-avatar {
  border: 1px solid #e4e7ed;
}

.username {
  font-size: 14px;
  color: #303133;
}

.dropdown-icon {
  color: #909399;
  font-size: 12px;
}

.body-container {
  height: calc(100vh - 60px);
}

.sidebar {
  background-color: #fff;
  border-right: 1px solid #e4e7ed;
  width: 260px;
  transition: width 0.3s;
  overflow: hidden;
}

.sidebar-menu {
  border-right: none;
  height: 100%;
}

.sidebar-menu:not(.el-menu--collapse) {
  width: 260px;
}

.main-content {
  background-color: #f5f5f5;
  padding: 0;
  overflow-y: auto;
}

.breadcrumb-container {
  background-color: #fff;
  padding: 12px 20px;
  border-bottom: 1px solid #e4e7ed;
}

.page-content {
  padding: 20px;
  min-height: calc(100vh - 60px - 45px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header {
    padding: 0 16px;
  }

  .system-name {
    display: none;
  }

  .username {
    display: none;
  }

  .page-content {
    padding: 16px;
  }
}
</style>
